package com.ruoyi.application.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpServletResponse;

import com.aliyun.ocr_api20210707.models.*;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.ruoyi.appointments.controller.AppointmentsController;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.application.domain.SysFormData;
import com.ruoyi.application.service.ISysFormDataService;
import com.ruoyi.application.util.AliyunAccountManager;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.application.domain.Application;
import com.ruoyi.application.service.IApplicationService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 报名信息Controller
 *
 * @author ruoyi
 * @date 2025-07-04
 */
@RestController
@RequestMapping("/application/application")
public class ApplicationController extends BaseController
{
    @Autowired
    private IApplicationService applicationService;

    @Autowired
    private ISysFormDataService sysFormDataService;

    /**
     * 查询报名信息列表
     */
    @PreAuthorize("@ss.hasPermi('application:application:list')")
    @GetMapping("/list")
    public TableDataInfo list(Application application)
    {
        startPage();
        List<Application> list = applicationService.selectApplicationList(application);
        return getDataTable(list);
    }

    /**
     * 导出报名信息列表
     */
    @PreAuthorize("@ss.hasPermi('application:application:export')")
    @Log(title = "报名信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Application application)
    {
        List<Application> list = applicationService.selectApplicationList(application);
        ExcelUtil<Application> util = new ExcelUtil<Application>(Application.class);
        util.exportExcel(response, list, "报名信息数据");
    }

    /**
     * 获取报名信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('application:application:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(applicationService.selectApplicationById(id));
    }

    /**
     * 新增报名信息
     */
    @PreAuthorize("@ss.hasPermi('application:application:add')")
    @Log(title = "报名信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Application application)
    {
        return toAjax(applicationService.insertApplication(application));
    }

    /**
     * 修改报名信息
     */
    @PreAuthorize("@ss.hasPermi('application:application:edit')")
    @Log(title = "报名信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Application application)
    {
        return toAjax(applicationService.updateApplication(application));
    }

    /**
     * 删除报名信息
     */
    @PreAuthorize("@ss.hasPermi('application:application:remove')")
    @Log(title = "报名信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(applicationService.deleteApplicationByIds(ids));
    }

    /**
     * 公开API - 提交报名信息（完整的三步注册流程）
     */
    @Anonymous
    @PostMapping("/submit")
    @CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.POST, RequestMethod.OPTIONS})
    public AjaxResult submitApplication(
            // 基本信息 - 第一步
            @RequestParam(value = "name", required = true) String name,
            @RequestParam(value = "idCardNumber", required = true) String idCardNumber,
            @RequestParam(value = "gender", required = true) String gender,
            @RequestParam(value = "birthDate", required = true) String birthDateStr,
            @RequestParam(value = "ethnicity", required = true) String ethnicity,
            @RequestParam(value = "idCardAddress", required = true) String idCardAddress,
            @RequestParam(value = "province", required = true) String province,
            @RequestParam(value = "city", required = true) String city,
            @RequestParam(value = "district", required = true) String district,
            @RequestParam(value = "detailAddress", required = true) String detailAddress,
            @RequestParam(value = "phone", required = true) String phone,
            @RequestParam(value = "familyName1", required = true) String familyName1,
            @RequestParam(value = "familyPhone1", required = true) String familyPhone1,
            @RequestParam(value = "familyName2", required = false) String familyName2,
            @RequestParam(value = "familyPhone2", required = false) String familyPhone2,
            @RequestParam(value = "graduateProvince", required = true) String graduateProvince,
            @RequestParam(value = "graduateCity", required = true) String graduateCity,
            @RequestParam(value = "graduateDistrict", required = true) String graduateDistrict,
            @RequestParam(value = "graduateSchool", required = true) String graduateSchool,
            @RequestParam(value = "graduateStatus", required = true) String graduateStatus,
            @RequestParam(value = "examNumber", required = false) String examNumber,
            @RequestParam(value = "targetSchool", required = true) String targetSchool,
            @RequestParam(value = "majorDirection", required = true) String majorDirection,
            @RequestParam(value = "targetMajor", required = true) String targetMajor,

            // 文件上传 - 第一步和第二步
            @RequestParam(value = "idCardImage", required = true) MultipartFile idCardImage,
            @RequestParam(value = "studentIdBackImage", required = true) MultipartFile studentIdBackImage,
            @RequestParam(value = "guardianIdFrontImage", required = true) MultipartFile guardianIdFrontImage,
            @RequestParam(value = "guardianIdBackImage", required = true) MultipartFile guardianIdBackImage,
            @RequestParam(value = "studentHouseholdFirstImage", required = true) MultipartFile studentHouseholdFirstImage,
            @RequestParam(value = "studentHouseholdInfoImage", required = true) MultipartFile studentHouseholdInfoImage,
            @RequestParam(value = "householderFirstImage", required = true) MultipartFile householderFirstImage,
            @RequestParam(value = "householderInfoImage", required = true) MultipartFile householderInfoImage,
            @RequestParam(value = "diplomaImage", required = true) MultipartFile diplomaImage) {

        try {
            // 创建新的Application对象
            Application application = new Application();

            // 设置基本信息
            application.setName(name);
            application.setIdCardNumber(idCardNumber);
            application.setGender(gender);

            // 转换日期字符串为Date对象
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date birthDate = dateFormat.parse(birthDateStr);
            application.setBirthDate(birthDate);

            application.setEthnicity(ethnicity);
            application.setIdCardAddress(idCardAddress);
            application.setProvince(province);
            application.setCity(city);
            application.setDistrict(district);
            application.setDetailAddress(detailAddress);
            application.setPhone(phone);
            application.setFamilyName1(familyName1);
            application.setFamilyPhone1(familyPhone1);
            application.setFamilyName2(familyName2);
            application.setFamilyPhone2(familyPhone2);
            application.setGraduateProvince(graduateProvince);
            application.setGraduateCity(graduateCity);
            application.setGraduateDistrict(graduateDistrict);
            application.setGraduateSchool(graduateSchool);
            application.setGraduateStatus(graduateStatus);
            application.setExamNumber(examNumber);
            application.setTargetSchool(targetSchool);
            application.setMajorDirection(majorDirection);
            application.setTargetMajor(targetMajor);

            // 设置注册状态为已完成
            application.setRegistrationStatus("completed");

            // 设置默认处理状态为"待处理"
            application.setStatus("待处理");

            // 设置创建时间和更新时间
            Date now = new Date();
            application.setCreatedAt(now);
            application.setUpdatedAt(now);

            // 上传所有文件
            String uploadBasePath = RuoYiConfig.getUploadPath() + "/application";

            // 上传身份证正面照片
            if (idCardImage != null && !idCardImage.isEmpty()) {
                String idCardFrontPath = FileUploadUtils.upload(uploadBasePath + "/idcard", true, idCardImage, null);
                application.setIdCardFrontImage(idCardFrontPath);
            } else {
                return AjaxResult.error("身份证正面照片不能为空");
            }

            // 上传身份证反面照片
            if (studentIdBackImage != null && !studentIdBackImage.isEmpty()) {
                String idCardBackPath = FileUploadUtils.upload(uploadBasePath + "/idcard", true, studentIdBackImage, null);
                application.setIdCardBackImage(idCardBackPath);
            } else {
                return AjaxResult.error("身份证反面照片不能为空");
            }

            // 上传监护人身份证正面照片
            if (guardianIdFrontImage != null && !guardianIdFrontImage.isEmpty()) {
                String guardianIdFrontPath = FileUploadUtils.upload(uploadBasePath + "/guardian", true, guardianIdFrontImage, null);
                application.setGuardianIdCardFrontImage(guardianIdFrontPath);
            } else {
                return AjaxResult.error("监护人身份证正面照片不能为空");
            }

            // 上传监护人身份证反面照片
            if (guardianIdBackImage != null && !guardianIdBackImage.isEmpty()) {
                String guardianIdBackPath = FileUploadUtils.upload(uploadBasePath + "/guardian", true, guardianIdBackImage, null);
                application.setGuardianIdCardBackImage(guardianIdBackPath);
            } else {
                return AjaxResult.error("监护人身份证反面照片不能为空");
            }

            // 上传户口本首页照片
            if (studentHouseholdFirstImage != null && !studentHouseholdFirstImage.isEmpty()) {
                String householdCoverPath = FileUploadUtils.upload(uploadBasePath + "/household", true, studentHouseholdFirstImage, null);
                application.setHouseholdCoverImage(householdCoverPath);
            } else {
                return AjaxResult.error("户口本首页照片不能为空");
            }

            // 上传户口本信息页照片
            if (studentHouseholdInfoImage != null && !studentHouseholdInfoImage.isEmpty()) {
                String householdInfoPath = FileUploadUtils.upload(uploadBasePath + "/household", true, studentHouseholdInfoImage, null);
                application.setHouseholdInfoImage(householdInfoPath);
            } else {
                return AjaxResult.error("户口本信息页照片不能为空");
            }

            // 上传户主户口本首页照片
            if (householderFirstImage != null && !householderFirstImage.isEmpty()) {
                String householderFirstPath = FileUploadUtils.upload(uploadBasePath + "/household", true, householderFirstImage, null);
                application.setHouseholdOwnerCoverImage(householderFirstPath);
            } else {
                return AjaxResult.error("户主户口本首页照片不能为空");
            }

            // 上传户主户口本信息页照片
            if (householderInfoImage != null && !householderInfoImage.isEmpty()) {
                String householderInfoPath = FileUploadUtils.upload(uploadBasePath + "/household", true, householderInfoImage, null);
                application.setHouseholdOwnerInfoImage(householderInfoPath);
            } else {
                return AjaxResult.error("户主户口本信息页照片不能为空");
            }

            // 上传毕业证照片
            if (diplomaImage != null && !diplomaImage.isEmpty()) {
                String diplomaPath = FileUploadUtils.upload(uploadBasePath + "/diploma", true, diplomaImage, null);
                application.setGraduationCertificateImage(diplomaPath);
            } else {
                return AjaxResult.error("毕业证照片不能为空");
            }

            // 保存报名信息
            applicationService.insertApplication(application);

            return AjaxResult.success("报名信息提交成功，我们将尽快与您联系！", application.getId());

        } catch (Exception e) {
            logger.error("提交报名信息失败", e);
            return AjaxResult.error("提交报名信息失败：" + e.getMessage());
        }
    }

    // ==================== 表单存储相关接口 ====================

    /**
     * 创建新的表单ID
     */
    @Anonymous
    @PostMapping("/form/create")
    @CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.POST, RequestMethod.OPTIONS})
    public AjaxResult createFormId() {
        try {
            String formId = UUID.randomUUID().toString().replace("-", "");
            Map<String, Object> result = new HashMap<>();
            result.put("formId", formId);
            return AjaxResult.success("表单ID创建成功", result);
        } catch (Exception e) {
            logger.error("创建表单ID失败", e);
            return AjaxResult.error("创建表单ID失败：" + e.getMessage());
        }
    }

    /**
     * 保存表单数据（分步保存）
     */
    @Anonymous
    @PostMapping("/form/save")
    @CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.POST, RequestMethod.OPTIONS})
    public AjaxResult saveFormData(@RequestBody Map<String, Object> requestData) {
        try {
            String formId = (String) requestData.get("formId");
            Integer currentStep = (Integer) requestData.get("currentStep");
            Map<String, Object> formData = (Map<String, Object>) requestData.get("formData");

            if (formId == null || formId.isEmpty()) {
                return AjaxResult.error("表单ID不能为空");
            }
            if (currentStep == null) {
                return AjaxResult.error("当前步骤不能为空");
            }
            if (formData == null) {
                return AjaxResult.error("表单数据不能为空");
            }

            // 将表单数据转换为JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String formContent = objectMapper.writeValueAsString(formData);

            // 保存或更新表单数据
            int result = sysFormDataService.saveOrUpdateFormData(formId, currentStep, formContent, "anonymous");

            if (result > 0) {
                Map<String, Object> responseData = new HashMap<>();
                responseData.put("formId", formId);
                responseData.put("currentStep", currentStep);
                return AjaxResult.success("表单数据保存成功", responseData);
            } else {
                return AjaxResult.error("表单数据保存失败");
            }
        } catch (Exception e) {
            logger.error("保存表单数据失败", e);
            return AjaxResult.error("保存表单数据失败：" + e.getMessage());
        }
    }

    /**
     * 获取表单数据
     */
    @Anonymous
    @GetMapping("/form/get/{formId}")
    @CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.GET, RequestMethod.OPTIONS})
    public AjaxResult getFormData(@PathVariable String formId) {
        try {
            if (formId == null || formId.isEmpty()) {
                return AjaxResult.error("表单ID不能为空");
            }

            SysFormData formData = sysFormDataService.selectSysFormDataByFormId(formId);
            if (formData == null) {
                return AjaxResult.error("表单数据不存在");
            }

            // 检查表单是否过期
            if (formData.getExpireTime() != null && formData.getExpireTime().before(new Date())) {
                return AjaxResult.error("表单已过期");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("formId", formData.getFormId());
            result.put("currentStep", formData.getCurrentStep());
            result.put("status", formData.getStatus());

            // 解析JSON格式的表单内容
            if (formData.getFormContent() != null && !formData.getFormContent().isEmpty()) {
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Object> formContent = objectMapper.readValue(formData.getFormContent(), Map.class);
                result.put("formData", formContent);
            }

            return AjaxResult.success("获取表单数据成功", result);
        } catch (Exception e) {
            logger.error("获取表单数据失败", e);
            return AjaxResult.error("获取表单数据失败：" + e.getMessage());
        }
    }

    /**
     * 提交完整表单数据
     */
    @Anonymous
    @PostMapping("/form/submit")
    @CrossOrigin(origins = "*", allowedHeaders = "*", methods = {RequestMethod.POST, RequestMethod.OPTIONS})
    public AjaxResult submitCompleteForm(@RequestBody Map<String, Object> requestData) {
        try {
            String formId = (String) requestData.get("formId");
            Map<String, Object> formData = (Map<String, Object>) requestData.get("formData");

            if (formId == null || formId.isEmpty()) {
                return AjaxResult.error("表单ID不能为空");
            }
            if (formData == null) {
                return AjaxResult.error("表单数据不能为空");
            }

            // 将表单数据转换为JSON字符串
            ObjectMapper objectMapper = new ObjectMapper();
            String formContent = objectMapper.writeValueAsString(formData);

            // 提交表单数据
            int result = sysFormDataService.submitFormData(formId, formContent, "anonymous");

            if (result > 0) {
                Map<String, Object> responseData = new HashMap<>();
                responseData.put("formId", formId);
                responseData.put("status", "submitted");
                return AjaxResult.success("表单提交成功", responseData);
            } else {
                return AjaxResult.error("表单提交失败");
            }
        } catch (Exception e) {
            logger.error("提交表单失败", e);
            return AjaxResult.error("提交表单失败：" + e.getMessage());
        }
    }

    /**
     * 创建阿里云OCR客户端（使用账号管理器）
     */
    public static com.aliyun.ocr_api20210707.Client createclient() throws Exception {
        // 获取当前可用账号
        AliyunAccountManager.AliyunAccount account = AliyunAccountManager.getInstance().getCurrentAccount();

        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                //您的 AccessKey ID
                .setAccessKeyId(account.getAccessKeyId())
                // 您的 AccessKey Secret
                .setAccessKeySecret(account.getAccessKeySecret());
        //访问的域名
        config.endpoint ="ocr-api.cn-hangzhou.aliyuncs.com";
        return new com.aliyun.ocr_api20210707.Client(config);
    }

    /**
     * 创建阿里云OCR客户端（兼容旧版本）
     */
    public static com.aliyun.ocr_api20210707.Client createclient(String accessKeyId, String accessKeySecret) throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                //您的 AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的 AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        //访问的域名
        config.endpoint ="ocr-api.cn-hangzhou.aliyuncs.com";
        return new com.aliyun.ocr_api20210707.Client(config);
    }
    /**
     * 身份证OCR识别接口
     */
    @PostMapping("/ocr")
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public AjaxResult ocr(@RequestParam("file") MultipartFile file) {
        System.out.println("=== OCR接口被调用 ===");
        System.out.println("接收到的文件: " + (file != null ? file.getOriginalFilename() : "null"));
        System.out.println("文件大小: " + (file != null ? file.getSize() : "null"));

        try {
            // 验证文件
            if (file == null || file.isEmpty()) {
                System.err.println("文件为空或null");
                return AjaxResult.error("请上传身份证图片文件");
            }

            // 验证文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return AjaxResult.error("请上传图片格式的身份证文件");
            }

            // 验证文件大小（限制5MB）
            if (file.getSize() > 5 * 1024 * 1024) {
                return AjaxResult.error("图片文件大小不能超过5MB");
            }

            // 使用账号管理器创建客户端
            com.aliyun.ocr_api20210707.Client client = createclient();

            java.io.InputStream bodyStream = file.getInputStream();

            com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest recognizeIdcardRequest = new com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest()
                    .setBody(bodyStream);

            com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

            RecognizeIdcardResponse response = client.recognizeIdcardWithOptions(recognizeIdcardRequest, runtime);

            // 请求成功后增加计数
            AliyunAccountManager.getInstance().useAccount();

            RecognizeIdcardResponseBody body = response.getBody();
            String result = body.data;

            return AjaxResult.success("身份证识别成功", result);

        } catch (TeaException error) {
            System.err.println("阿里云OCR识别错误: " + error.getMessage());
            if (error.getData() != null && error.getData().get("Recommend") != null) {
                System.err.println("建议: " + error.getData().get("Recommend"));
            }
            return AjaxResult.error("不是有效身份证件,请重新上传！");
        } catch (Exception e) {
            System.err.println("OCR接口异常: " + e.getMessage());
            e.printStackTrace();
            return AjaxResult.error("身份证识别服务异常，请稍后重试");
        }
    }


    /**
     * 识别户口本图片
     *
     * @param file 户口本图片文件
     * @param isResidentPage 是否为常住人口登记卡页面
     * @return 识别结果JSON字符串
     * @throws IllegalArgumentException 图片路径无效
     * @throws IOException 文件读取异常
     * @throws TeaException API调用异常
     */
    @PostMapping("/recognizeHousehold")
    @CrossOrigin(origins = "*", allowedHeaders = "*")
    public AjaxResult recognizeHousehold(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "isResidentPage", defaultValue = "true") boolean isResidentPage) {

        try {
            // 1. 验证文件（保持不变）
            if (file == null || file.isEmpty()) {
                return AjaxResult.error("请上传户口本图片文件");
            }
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return AjaxResult.error("请上传图片格式的文件（支持jpg、png等）");
            }
            if (file.getSize() > 5 * 1024 * 1024) {
                return AjaxResult.error("图片文件大小不能超过5MB");
            }

            // 2. 初始化客户端（使用账号管理器）
            com.aliyun.ocr_api20210707.Client client = createclient();

            // 3. 调用阿里云OCR接口
            try (InputStream bodyStream = file.getInputStream()) {
                RecognizeHouseholdRequest request = new RecognizeHouseholdRequest()
                        .setBody(bodyStream)
                        .setIsResidentPage(isResidentPage);
                RuntimeOptions runtime = new RuntimeOptions();
                RecognizeHouseholdResponse response = client.recognizeHouseholdWithOptions(request, runtime);

                // 请求成功后增加计数
                AliyunAccountManager.getInstance().useAccount();

                // 4. 提取结构化数据（关键优化点）
                RecognizeHouseholdResponseBody body = response.getBody();
                // 将阿里云返回的识别结果转换为JSON字符串（或自定义DTO）
                String jsonResult = body.data; // 原始识别结果（JSON格式字符串）
                // 若需要进一步解析，可使用JSON工具转为Map或实体类
                // Map<String, Object> resultMap = JSON.parseObject(jsonResult, Map.class);

                // 5. 返回结构化数据
                return AjaxResult.success("户口本识别成功", jsonResult);
            }

        } catch (TeaException error) {
            return AjaxResult.error("不是有效户口本，请重新上传！");
        } catch (Exception e) {
            return AjaxResult.error("系统异常：" + e.getMessage());
        }
    }

    /**
     * 获取阿里云账号使用状态
     */
    @PreAuthorize("@ss.hasPermi('application:application:query')")
    @GetMapping("/account/status")
    public AjaxResult getAccountStatus() {
        try {
            String status = AliyunAccountManager.getInstance().getAccountStatus();
            Map<String, Object> result = new HashMap<>();
            result.put("status", status);
            result.put("currentIndex", AliyunAccountManager.getInstance().getCurrentAccountIndex());
            result.put("totalAccounts", AliyunAccountManager.getInstance().getAccountCount());
            return AjaxResult.success("获取账号状态成功", result);
        } catch (Exception e) {
            return AjaxResult.error("获取账号状态失败：" + e.getMessage());
        }
    }

    /**
     * 重置所有账号请求计数
     */
    @PreAuthorize("@ss.hasPermi('application:application:edit')")
    @PostMapping("/account/reset")
    public AjaxResult resetAccountCount() {
        try {
            AliyunAccountManager.getInstance().resetAllAccounts();
            return AjaxResult.success("重置账号计数成功");
        } catch (Exception e) {
            return AjaxResult.error("重置账号计数失败：" + e.getMessage());
        }
    }

    /**
     * 手动切换到下一个账号
     */
    @PreAuthorize("@ss.hasPermi('application:application:edit')")
    @PostMapping("/account/switch")
    public AjaxResult switchAccount() {
        try {
            AliyunAccountManager.AliyunAccount currentAccount = AliyunAccountManager.getInstance().getCurrentAccount();
            Map<String, Object> result = new HashMap<>();
            result.put("currentAccount", currentAccount.toString());
            result.put("currentIndex", AliyunAccountManager.getInstance().getCurrentAccountIndex());
            return AjaxResult.success("切换账号成功", result);
        } catch (Exception e) {
            return AjaxResult.error("切换账号失败：" + e.getMessage());
        }
    }
}
